import requests
import json

base_url = "http://localhost:8080/api/users"


def test_user_register():
    """测试用户注册"""
    print("=== 测试用户注册 ===")

    # 测试数据
    register_data = {"username": "testuser123", "password": "123456"}

    try:
        response = requests.post(
            f"{base_url}/register",
            json=register_data,
            headers={"Content-Type": "application/json"},
        )

        print(f"状态码: {response.status_code}")
        print(f"响应内容: {response.json()}")

        if response.status_code == 200:
            print("✅ 注册成功")
            return True
        else:
            print("❌ 注册失败")
            return False

    except Exception as e:
        print(f"❌ 注册请求异常: {e}")
        return False


def test_user_login():
    """测试用户登录"""
    print("\n=== 测试用户登录 ===")

    # 测试数据
    login_data = {"username": "testuser123", "password": "123456"}

    try:
        response = requests.post(
            f"{base_url}/login",
            json=login_data,
            headers={"Content-Type": "application/json"},
        )

        print(f"状态码: {response.status_code}")
        print(f"响应内容: {response.json()}")

        if response.status_code == 200:
            print("✅ 登录成功")
            # 返回token供后续测试使用
            return response.json().get("token")
        else:
            print("❌ 登录失败")
            return None

    except Exception as e:
        print(f"❌ 登录请求异常: {e}")
        return None


def test_duplicate_register():
    """测试重复注册"""
    print("\n=== 测试重复注册 ===")

    # 使用相同的用户名注册
    register_data = {"username": "testuser123", "password": "123456"}

    try:
        response = requests.post(
            f"{base_url}/register",
            json=register_data,
            headers={"Content-Type": "application/json"},
        )

        print(f"状态码: {response.status_code}")
        print(f"响应内容: {response.json()}")

        if response.status_code == 400:
            print("✅ 重复注册验证成功")
        else:
            print("❌ 重复注册验证失败")

    except Exception as e:
        print(f"❌ 重复注册请求异常: {e}")


def test_wrong_login():
    """测试错误登录"""
    print("\n=== 测试错误登录 ===")

    # 错误的密码
    login_data = {"username": "testuser123", "password": "wrongpassword"}

    try:
        response = requests.post(
            f"{base_url}/login",
            json=login_data,
            headers={"Content-Type": "application/json"},
        )

        print(f"状态码: {response.status_code}")
        print(f"响应内容: {response.json()}")

        if response.status_code == 401:
            print("✅ 错误登录验证成功")
        else:
            print("❌ 错误登录验证失败")

    except Exception as e:
        print(f"❌ 错误登录请求异常: {e}")


def test_get_user_info(token):
    """测试获取用户信息"""
    print("\n=== 测试获取用户信息 ===")

    if not token:
        print("❌ 没有有效的token，跳过测试")
        return

    headers = {
        "Authorization": f"Bearer {token}",
        "Content-Type": "application/json",
    }
    try:
        response = requests.get(f"{base_url}/get", headers=headers)

        print(f"状态码: {response.status_code}")
        print(f"响应内容: {response.json()}")

        if response.status_code == 200:
            print("✅ 获取用户信息成功")
        else:
            print("❌ 获取用户信息失败")

    except Exception as e:
        print(f"❌ 获取用户信息请求异常: {e}")


def test_update_user_info(token):
    """测试更新用户信息"""
    print("\n=== 测试更新用户信息 ===")

    if not token:
        print("❌ 没有有效的token，跳过测试")
        return

    # 首先需要获取用户ID
    try:
        get_response = requests.get(
            f"{base_url}/get",
            headers={
                "Authorization": f"Bearer {token}",
                "Content-Type": "application/json",
            },
        )

        if get_response.status_code != 200:
            print("❌ 无法获取用户信息进行更新测试")
            return

        user_data = get_response.json().get("user_data")
        user_id = user_data.get("user_id")

        # 更新用户信息
        update_data = {
            "user_id": user_id,
            "nickname": "测试昵称",
            "age": 25,
            "gender": "男",
        }

        response = requests.post(
            f"{base_url}/update",
            json=update_data,
            headers={
                "Authorization": f"Bearer {token}",
                "Content-Type": "application/json",
            },
        )

        print(f"状态码: {response.status_code}")
        print(f"响应内容: {response.json()}")

        if response.status_code == 200:
            print("✅ 更新用户信息成功")
        else:
            print("❌ 更新用户信息失败")

    except Exception as e:
        print(f"❌ 更新用户信息请求异常: {e}")


def run_all_tests():
    """运行所有测试"""
    print("开始用户功能测试...")
    print("=" * 50)

    # 1. 测试注册
    register_success = test_user_register()

    # 2. 测试重复注册
    test_duplicate_register()

    # 3. 测试登录
    token = test_user_login()

    # 4. 测试错误登录
    test_wrong_login()

    # 5. 测试获取用户信息
    test_get_user_info(token)

    # 6. 测试更新用户信息
    test_update_user_info(token)

    print("\n" + "=" * 50)
    print("用户功能测试完成")


if __name__ == "__main__":
    run_all_tests()
